﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace Eksponent.RazorRocks.Poco
{
    internal class PocoTypeHelper
    {
        private static ConcurrentDictionary<Type, TypeInfo> _typeInfos = new ConcurrentDictionary<Type, TypeInfo>();

        internal static TypeInfo GetTypeInfo(object o)
        {
            Type t = o.GetType();

            TypeInfo ti;
            if (_typeInfos.TryGetValue(t, out ti))
            {
                return ti;
            }

            lock (t)
            {
                if (!_typeInfos.TryGetValue(t, out ti))
                {
                    var baseNames = new List<string>();
                    var p = t.BaseType;
                    while (p != null)
                    {
                        baseNames.Add(p.Name);
                        p = p.BaseType;
                    }

                    baseNames.AddRange(t.GetInterfaces().Select(i => i.Name));

                    ti = new TypeInfo(t.Name, baseNames);
                    _typeInfos.TryAdd(t, ti);
                }
            }

            return ti;
        }

    }

    public class PocoTemplateMathcer<TBase> : TemplateMatcher<TBase> where TBase : class
    {
        

        public PocoTemplateMathcer(string basePath)
            : base(PocoTypeHelper.GetTypeInfo, basePath)
        {
        }
    }
}